package cn.westv.scps.web.controller.dict;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.domain.SysDict;
import cn.westv.scps.domain.SysDictItem;
import cn.westv.scps.service.sys.dict.ISysDictItemService;
import cn.westv.scps.service.sys.dict.ISysDictService;
import cn.westv.scps.utils.Page;
import cn.westv.scps.utils.StringUtils;
import cn.westv.scps.web.controller.base.AbstractController;
import cn.westv.scps.web.controller.dict.vo.DictItemVO;
import cn.westv.scps.web.controller.dict.vo.DictVO;

/**
 * 这是有关数据字典的http接口
 */
@Controller
@RequestMapping("/sys/dict")
public class DictController extends AbstractController<DictController> {
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ISysDictItemService sysDictItemService;

	
	@RequestMapping("/index.cgi")
	public String toIndex_cgi() {
		return "forward:/WEB-INF/page/sys/dict/dictIndex.jsp";
	}

	@RequestMapping("/edit.cgi")
	public String toEdit_cgi() {
		return "forward:/WEB-INF/page/sys/dict/dictEdit.jsp";
	}

	@RequestMapping("/item/index.cgi")
	public String itemList_cgi() {
		return "forward:/WEB-INF/page/sys/dict/dictItemIndex.jsp";
	}

	@RequestMapping("/item/edit.cgi")
	public String toItemEdit_cgi() {
		return "forward:/WEB-INF/page/sys/dict/dictItemEdit.jsp";
	}

	/**
	 * 分页查询字典类别
	 * 
	 * @param dictVO
	 *            这是筛选条件的数据包，当中有一个SysDict类，参数名为sysDictEntity，SysDict类中的字段的值就是筛选的条件<br>
	 *            例如：要根据dictName进行筛选，则参数为sysDictEntity.dictName=#dictName#
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/pagelist", method = RequestMethod.POST) //
	public Map<String, Object> dictFindPage(DictVO dictVO, Page<SysDict> page) {
		try {
			String hql = "from SysDict where 1 = 1 ";
			List<Object> params = new ArrayList<>();
			SysDict sysDictEntity = dictVO.getSysDict();
			if (sysDictEntity != null) {
				String description = sysDictEntity.getDescription();
				if (StringUtils.isNotBlank(description)) {
					hql += " and description like ?";
					params.add("%" + description + "%");
				}
				String dictName = sysDictEntity.getDictName();
				if (StringUtils.isNotBlank(dictName)) {
					hql += " and dictName like ?";
					params.add("%" + dictName + "%");
				}
				String dictCode = sysDictEntity.getDictCode();
				if (StringUtils.isNotBlank(dictCode)) {
					hql += " and dictCode like ?";
					params.add("%" + dictCode + "%");
				}
			}
			Page<SysDict> findPage = sysDictService.findPage(hql, page, SysDict.class, params.toArray());
			findPage.setUrl("dict/pagelist");
			List<SysDict> results = findPage.getResults();
			for (SysDict resEntity : results) {
				resEntity.setSysDictItems(null);
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 新增或修改字典类别，保存编辑的方法
	 * 
	 * @param dictVO
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveDictType(DictVO dictVO, HttpServletRequest request) {
		try {
			SysDict sysDictEntity = dictVO.getSysDict();
			SysDict sysDictEntityDB = null;
			if (sysDictEntity != null) {
				String msg = "";
				if (StringUtils.isEmpty(sysDictEntity.getDictId())) {
					// 新增
					List<SysDict> find = sysDictService.find("from SysDict where dictCode = ?", SysDict.class,
							new Object[] { sysDictEntity.getDictCode() });// 根据code查询，判断是否存在code重复
					if (find != null && find.size() > 0) {
						return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，code重复！", null);
					}
					sysDictEntity.setDictId(null);
					sysDictEntityDB = sysDictEntity;
					msg = returnMsg("add_succeed");
				} else {
					// 修改
					sysDictEntityDB = sysDictService.get(SysDict.class, sysDictEntity.getDictId());//原数据
					String description = sysDictEntity.getDescription();
					String dictCode = sysDictEntity.getDictCode();
					if (!dictCode.equals(sysDictEntityDB.getDictCode())) {// 判断code是否被修改
						return ajaxReturnMap(OP_STATUS_FAILD, "错误，code不能修改！", null);
					}
					sysDictEntityDB.setDescription(description);
					String dictName = sysDictEntity.getDictName();
					sysDictEntityDB.setDictName(dictName);
					msg = returnMsg("update_succeed");
				}
				sysDictService.saveOrUpdate(sysDictEntityDB);
				return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 删除字典类别
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public Map<String, Object> delDictType(String ids) {
		try {
			String[] idArr = null;
			if (StringUtils.isNotBlank(ids)) {
				idArr = ids.split(",");
			}
			String msg = "";
			sysDictService.delete(SysDict.class, idArr);
			msg = returnMsg("del_succeed");
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 获取数据字典
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/detail")
	public Map<String, Object> dictDetail(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL + "（id为空）", null);
		}
		try {
			SysDict sysDict = sysDictService.get(SysDict.class, id);
			sysDict.setSysDictItems(null);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", sysDict);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}
	
	
	/**
	 * 获取字典元素列表
	 * 
	 * @param DictItemVO
	 * @param dictVO
	 * @param vague
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/item/pagelist", method = RequestMethod.POST) //
	public Map<String, Object> dictItemFindPage(DictItemVO DictItemVO, DictVO dictVO, Boolean vague, Page page) {
		if (vague == null) {
			vague = true;
		}
		try {
			String hql = "from SysDictItem where 1 = 1 ";
			List<Object> params = new ArrayList<>();
			SysDict sysDictEntity = dictVO.getSysDict();
			if (sysDictEntity != null) {
				String operation = "";
				String paramAssist = "";
				if (vague) {
					operation = "like";
					paramAssist = "%";
				} else {
					operation = "=";
				}

				String dictId = sysDictEntity.getDictId();
				if (StringUtils.isNotBlank(dictId)) {
					hql += " and sysDict.dictId = ?";
					params.add(dictId);
				}
				String dictCode = sysDictEntity.getDictCode();
				if (StringUtils.isNotBlank(dictCode)) {
					hql += " and sysDict.dictCode " + operation + " ?";
					params.add(paramAssist + dictCode + paramAssist);
				}
				SysDictItem sysDictItemEntity = DictItemVO.getSysDictItem();
				if (sysDictItemEntity != null) {

					String itemCode = sysDictItemEntity.getItemCode();
					if (StringUtils.isNotBlank(itemCode)) {
						hql += " and itemCode " + operation + " ?";
						params.add(paramAssist + itemCode + paramAssist);
					}
					String itemName = sysDictItemEntity.getItemName();
					if (StringUtils.isNotBlank(itemName)) {
						hql += " and itemName " + operation + " ?";
						params.add(paramAssist + itemName + paramAssist);
					}
					String itemValue = sysDictItemEntity.getItemValue();
					if (StringUtils.isNotBlank(itemValue)) {
						hql += " and itemValue " + operation + " ?";
						params.add(paramAssist + itemValue + paramAssist);
					}
				}

			}
			Page<SysDictItem> findPage = sysDictItemService.findPage(hql, page, SysDictItem.class, params.toArray());
			List<SysDictItem> list = findPage.getResults();
			for (SysDictItem object : list) {
				object.setSysDict(null);
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 添加或者修改字典元素，保存编辑的方法
	 * 
	 * @param DictItemVO
	 * @param dictVO
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/item/save", method = RequestMethod.POST) //
	public Map<String, Object> saveDictItem(DictItemVO DictItemVO, DictVO dictVO) {
		try {
			String msg = "";

			SysDictItem sysDictItemEntity = DictItemVO.getSysDictItem();
			if (sysDictItemEntity != null) {
				String dictId = "";
				SysDict sysDictEntity = dictVO.getSysDict();
				if (sysDictEntity != null) {
					dictId = sysDictEntity.getDictId();
				}
				if (StringUtils.isNotBlank(dictId)) {// 判断是否选中了字典类别
					SysDict sysDictEntityDB = sysDictService.get(SysDict.class, dictId);
					if (sysDictEntityDB != null) {// 判断数据库中是否存在这个类别
						Set<SysDictItem> sysDictItems = sysDictEntityDB.getSysDictItems();
						String itemId = sysDictItemEntity.getItemId();
						if (StringUtils.isEmpty(itemId)) {// 添加字典元素
							String itemCode = sysDictItemEntity.getItemCode();
							String itemValue = sysDictItemEntity.getItemValue();
							String itemName = sysDictItemEntity.getItemName();
							if (StringUtils.isNotBlank(itemCode) && StringUtils.isNotBlank(itemValue)
									&& StringUtils.isNotBlank(itemName)) {// 判断必填项目
								List<SysDictItem> find = sysDictItemService.find(
										"from SysDictItem where itemCode = ? or itemValue = ?", SysDictItem.class,
										new Object[] { sysDictItemEntity.getItemCode(),
												sysDictItemEntity.getItemValue() });
								if (find != null && find.size() > 0) {
									return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，code（编码）或者value（值）已经存在！", null);
								}
								sysDictItemEntity.setItemId(null);
								sysDictItemEntity.setItemEnable("1");
								sysDictItemEntity.setSysDict(sysDictEntityDB);
								sysDictItemService.saveOrUpdate(sysDictItemEntity);
								msg = returnMsg("add_succeed");
							} else {
								return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，名称（必填）、编码（必填、唯一）、值（必填、唯一）！", null);
							}
						} else {// 修改字典元素
							SysDictItem sysDictItemEntityDB = sysDictItemService.get(SysDictItem.class,
									sysDictItemEntity.getItemId());
							if (sysDictItemEntityDB == null) {// 判断数据库中是否有这条数据
								return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，没有这条数据！", null);
							}
							String itemCode = sysDictItemEntity.getItemCode();
							String itemValue = sysDictItemEntity.getItemValue();
							String itemName = sysDictItemEntity.getItemName();
							if (StringUtils.isNotBlank(itemCode) && StringUtils.isNotBlank(itemValue)
									&& StringUtils.isNotBlank(itemName)) {// 判断必填项目
								if (!itemCode.equals(sysDictItemEntityDB.getItemCode())) {// 判断code是否被更改
									return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，编码不能被修改！", null);
								}
								if (!itemName.equals(sysDictItemEntityDB.getItemValue())) {
									List<SysDictItem> find = sysDictItemService.find(
											"from SysDictItem where itemValue = ?", SysDictItem.class,
											new Object[] { itemName });
									if (find != null && find.size() > 0) {
										return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，值重复！", null);
									}
								}
								if (StringUtils.isNotBlank(itemValue)) {
									sysDictItemEntityDB.setItemValue(itemValue);
								}
								if (StringUtils.isNotBlank(itemName)) {
									sysDictItemEntityDB.setItemName(itemName);
								}
								Integer itemRank = sysDictItemEntity.getItemRank();
								if (itemRank != null) {
									sysDictItemEntityDB.setItemRank(itemRank);
								}
								String itemEnable = sysDictItemEntity.getItemEnable();
								if (StringUtils.isNotBlank(itemEnable)) {
									sysDictItemEntityDB.setItemEnable(itemEnable);
								}
								msg = returnMsg(ConfigCodeConstant.UPDATE_SUCCEED);
								sysDictItemService.saveOrUpdate(sysDictItemEntityDB);
							} else {
								return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，名称（必填）、编码（必填、唯一）、值（必填、唯一）！", null);
							}

						}
						return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
					} else {
						return ajaxReturnMap(OP_STATUS_FAILD, "操作失败，没有对应的字典类别，请先添加字典类别！", null);
					}
				} else {
					return ajaxReturnMap(OP_STATUS_FAILD, "操作失败，请选中字典类别！", null);
				}
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 删除字典元素
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/item/del")
	public Map<String, Object> delDictItem(String ids) {
		try {
			String[] idArr = null;
			if (StringUtils.isNotBlank(ids)) {
				idArr = ids.split(",");
			}
			sysDictItemService.delete(SysDictItem.class, idArr);
			return ajaxReturnMap(OP_STATUS_SUCCESS, returnMsg(ConfigCodeConstant.DEL_SUCCEED), null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 获取所有的数据字典
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/all")
	public Map<String, Object> findAllDict(DictVO dictVO) {
		try {
			String hql = "from SysDict where 1 = 1 ";
			List<Object> param = new ArrayList<>();
			if (dictVO != null) {
				SysDict sysDictEntity = dictVO.getSysDict();
				if (sysDictEntity != null) {
					String dictId = sysDictEntity.getDictId();
					if (StringUtils.isNotBlank(dictId)) {
						hql += " and dictId = ? ";
						param.add(dictId);
					}
					String dictCode = sysDictEntity.getDictCode();
					if (StringUtils.isNotBlank(dictCode)) {
						hql += " and dictCode = ? ";
						param.add(dictCode);
					}
					String dictName = sysDictEntity.getDictName();
					if (StringUtils.isNotBlank(dictName)) {
						hql += " and dictName = ? ";
						param.add(dictName);
					}
				}
			}
			List<SysDict> list = sysDictService.find(hql, SysDict.class, param.toArray());
			for (SysDict sysDictEntity : list) {
				// Set<SysDictItem> sysDictItems =
				// sysDictEntity.getSysDictItems();
				// for (SysDictItem sysDictItemEntity : sysDictItems) {
				// String itemEnable = sysDictItemEntity.getItemEnable();
				// if (itemEnable.equals("0")) {
				// sysDictItems.remove(sysDictItemEntity);
				// }
				// }
				Set<SysDictItem> sysDictItems = sysDictEntity.getSysDictItems();
				for (SysDictItem sysDictItem : sysDictItems) {
					sysDictItem.setSysDict(null);
				}
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", list);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 获取字典元素
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/tiem/detail")
	public Map<String, Object> dictItemDetail(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL + "（id为空）", null);
		}
		try {
			SysDictItem sysDictItemEntity = sysDictItemService.get(SysDictItem.class, id);
			sysDictItemEntity.setSysDict(null);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", sysDictItemEntity);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}
}
